package com.jeecms.wicool.action.car;

import static com.jeecms.common.page.SimplePage.cpn;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.wicool.entity.car.CarBrand;
import com.jeecms.wicool.entity.car.CarImg;
import com.jeecms.wicool.entity.car.CarParam;
import com.jeecms.wicool.entity.car.CarSeries;
import com.jeecms.wicool.entity.car.CarType;
import com.jeecms.wicool.entity.car.UsedCar;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.manager.car.CarBrandMng;
import com.jeecms.wicool.manager.car.CarImgMng;
import com.jeecms.wicool.manager.car.CarParamMng;
import com.jeecms.wicool.manager.car.CarSeriesMng;
import com.jeecms.wicool.manager.car.CarTypeMng;
import com.jeecms.wicool.manager.car.UsedCarMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;

@Controller
public class CarTypeAct {
	private static final Logger log = LoggerFactory.getLogger(CarTypeAct.class);

	@RequestMapping("/carType/v_list.do")
	public String list(String typeName,Integer carBrandId,Integer carSeriesId,Integer year ,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage( typeName, carBrandId, carSeriesId, year ,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("listCarBrand",listCarBrand);
		model.addAttribute("listCarSeries",listCarSeries);
		
		model.addAttribute("typeName",typeName);
		model.addAttribute("carBrandId",carBrandId);
		model.addAttribute("carSeriesId",carSeriesId);
		model.addAttribute("year",year);
		return "car/list_carType";
	}
	@RequestMapping("/carType/v_toEditCarType.do")
	public String toEditCarType(Integer id,String flag, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("carType_id",id);
		if(flag!=null&&flag.equals("saveSuccess")){
		model.addAttribute("message", "保存车型成功，请录入该车型详细参数！");
		}
		return "car/to_edit_carType";
	}
	@RequestMapping("/carType/v_edit.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarType carType = manager.findById(id);
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("carType",carType);
		model.addAttribute("listShop",listShop);
		model.addAttribute("listCarBrand",listCarBrand);
		model.addAttribute("listCarSeries",listCarSeries);
		return "car/edit_carType";
	}
	@RequestMapping("/carType/v_edit_carParam.do")
	public String editCarParam(Integer carTypeId, CarParam bean,HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(carTypeId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarType carType = manager.findById(carTypeId);
		CarParam carParam = carType.getCarParam();
		if(carParam==null){
			carParam=new CarParam();
		}
		carParam.setCarType(carType);
		if(bean.getId()!=null){
			model.addAttribute("carParam",bean);
		}else{
		model.addAttribute("carParam",carParam);
		}
		return "car/edit_carParam";
	}
	@RequestMapping("/carType/v_toView.do")
	public String toView(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("carType_id",id);
		return "car/to_view_carType";
	}
	@RequestMapping("/carType/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarType carType = manager.findById(id);
		model.addAttribute("carType",carType);
		return "car/view_carType";
	}
	@RequestMapping("/carType/v_view_carParam.do")
	public String viewCarParm(Integer carTypeId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(carTypeId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarType carType = manager.findById(carTypeId);
		CarParam carParam = carType.getCarParam();
		model.addAttribute("carParam",carParam);
		return "car/view_carParam";
	}
	@RequestMapping("/carType/o_save.do")
	public String save(CarType bean, Integer shopId,Integer carBrandId,Integer carSeriesId,String[] imgUrls, String[] imgNames,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(imgUrls!=null&&imgUrls.length>0){
			Set<CarImg> listCarImgs=new HashSet<CarImg>();
			for(int i=0;i<imgUrls.length;i++){
				CarImg carImg=new CarImg();
				carImg.setCarCate(Short.parseShort("1"));
				carImg.setCarType(bean);
				carImg.setImgName(imgNames[i]);
				carImg.setImgUrl(imgUrls[i]);
				listCarImgs.add(carImg);
			}
			bean.setCarImgs(listCarImgs);
		}
		bean = manager.save(bean,shopId,carBrandId,carSeriesId);
		updateCarSeriesPrice(bean);
		log.info("save CarType id={}", bean.getId());
		cmsLogMng.operating(request, "CarType.log.save",  "id=" + bean.getId());
		//return "redirect:v_list.do";
		return this.toEditCarType(bean.getId(),"saveSuccess", request, model);
	}
	@RequestMapping("/carType/o_update.do")
	public String update(CarType bean,Integer shopId ,Integer carBrandId,Integer carSeriesId,String[] imgUrls, String[] imgNames,
			Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		
		//处理图片集
		//删除原有的图片集
		CarType c=manager.findById(bean.getId());
		if(c.getCarImgs()!=null&&c.getCarImgs().size()>0){
			Set<CarImg>s= new HashSet<CarImg>();
				s.addAll(c.getCarImgs());
			for(CarImg i:s){
				c.getCarImgs().remove(i);
				i.setCarType(null);
				carImgMng.deleteById(i.getId());
			}
		}
		if(imgUrls!=null&&imgUrls.length>0){
			Set<CarImg> listCarImgs=new HashSet<CarImg>();
			for(int i=0;i<imgUrls.length;i++){
				CarImg carImg=new CarImg();
				carImg.setCarCate(Short.parseShort("1"));
				carImg.setCarType(bean);
				carImg.setImgName(imgNames[i]);
				carImg.setImgUrl(imgUrls[i]);
				listCarImgs.add(carImg);
			}
			bean.setCarImgs(listCarImgs);
		}
		//****
		bean=manager.update(bean,shopId,carBrandId,carSeriesId);
		updateCarSeriesPrice(bean);
		model.addAttribute("message", "global.success");
		log.info("update CarType success. id={}", bean.getId());
		cmsLogMng.operating(request, "CarType.log.update",  "id=" + bean.getId());
		return list(null,null,null,null,pageNo,request, model);
	}
	@RequestMapping("/carType/o_updateCarParam.do")
	public String updateCarParam(CarParam bean,Integer carTypeId,Integer pageNo,HttpServletRequest request,ModelMap model) {
		CarType carType=manager.findById(carTypeId);
		bean.setCarType(carType);
		if(bean.getId()==null){  //保存
			bean = carParamMng.save(bean);
		}else{ //更新
			bean=carParamMng.update(bean);
		}
		model.addAttribute("message", "global.success");
		return editCarParam(carTypeId,bean, request, model);
	}
	@RequestMapping("/carType/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		CarType carType = new CarType();
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		List<CarBrand> listCarBrand=carBrandMng.getAll(CmsUtils.getUser(request));
		List<CarSeries> listCarSeries=carSeriesMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("carType", carType);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listCarBrand", listCarBrand);
		model.addAttribute("listCarSeries", listCarSeries);
		return "car/add_carType";
	}
	
	@RequestMapping("/carType/o_delete.do")
	public String delete(Integer[] ids, String typeName,Integer carBrandId,Integer carSeriesId,Integer year ,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for(int i=0;i<ids.length;i++){
			List<UsedCar> list= usedCarMng.findByCarTypeId(ids[i]);
			if(list!=null&&list.size()>0){
				model.addAttribute("message", "delete.failed.isHaveChildren");
				return list(typeName,carBrandId,carSeriesId,year,pageNo, request, model);
			}
		}
		
		CarType[] beans = manager.deleteByIds(ids);
		for (CarType bean : beans) {
			log.info("delete CarType id={}", bean.getId());
			cmsLogMng.operating(request, "CarType.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getTypeName());
		}
		return list(typeName,carBrandId,carSeriesId,year,pageNo, request, model);
	}
	@RequestMapping("/carType/getCarSeries.do")
	public void getCarSeries(HttpServletRequest request,HttpServletResponse response,String bid) throws Exception{
		List<CarSeries> carSeriesList = new ArrayList<CarSeries>();
		if(StringUtils.isNotBlank(bid)){
			carSeriesList = carSeriesMng.getCarSeriesByCarBrand(Integer.parseInt(bid),CmsUtils.getUser(request));
		}
		JSONArray result = new JSONArray();
		JSONObject obj = null;
		for (CarSeries s : carSeriesList) {
			obj = new JSONObject();
			obj.put("sid", s.getId());
			obj.put("sname", s.getShortName());
			result.put(obj);
		}
		ResponseUtils.renderJson(response, result.toString());
	}
	private WebErrors validateSave(CarType bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		CarType entity = manager.findById(id);
		if (errors.ifNotExist(entity, CarType.class, id)) {
			return true;
		}
		return false;
	}
	/**
	 * 根据车型价格同步对应车系价格上线下线
	 * @param bean
	 */
	private void updateCarSeriesPrice(CarType bean){
		BigDecimal p1= bean.getPriceGuide(); 
		BigDecimal p2= bean.getPriceSale();
		CarSeries cs=carSeriesMng.findById(bean.getCarSeries().getId());
		BigDecimal ceiling = cs.getPriceCeiling();//上线
		BigDecimal floor = cs.getPriceFloor();//下线
		BigDecimal up = ceiling;
		BigDecimal down =floor;
		if(up.compareTo(p1)==-1){  //up小
			up=p1;
		}if(up.compareTo(p2)==-1){
			up=p2;
		}
		if(down.compareTo(p1)==1){//down大 
			down=p1;
		}if(down.compareTo(p2)==1){
			down=p2;
		}
		if(ceiling.compareTo(up)!=0||floor.compareTo(down)!=0){  //有变化需要更新
			cs.setPriceCeiling(up);
			cs.setPriceFloor(down);
			carSeriesMng.update(cs, cs.getShop().getId(), cs.getCarBrand().getId());
			}
	}
	@Autowired
	private CarTypeMng manager;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private CarBrandMng carBrandMng;
	@Autowired
	private CarSeriesMng carSeriesMng;
	@Autowired
	private CarParamMng carParamMng;
	@Autowired
	private CarImgMng carImgMng;
	@Autowired
	private UsedCarMng usedCarMng;
}
